var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');
var cheerio = require('cheerio');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

function main(options) {
    const offset = options.offset ? options.offset : 0;
    // let album = {};
    // let songList=[];

    var ipList = [];
    var ipIndex = 0;
    var proxy = '';

    function changeIp() {
        if (ipIndex < ipList.length - 1) {
            ipIndex += 1;
        } else {
            ipIndex = 0;
        }
        setProxy();
    }

    function setProxy() {
        var item = ipList[ipIndex];
        console.log(item);

        var ip = item.ip;
        var port = item.port;

        proxy = `http://${ip}:${port}`;
        console.log('proxy');
        console.log(proxy);
        console.log();

    }

    function getIpList() {
        var connection1 = mysql.createConnection(mysqlProxy);
        var query1 = 'select * from ip_table1 where success_count>6 ;';
        connection1.connect();
        connection1.query(query1, function (err, res) {
            if (err) {
                console.log('query1 error');
                setTimeout(() => {
                    getIpList();
                }, 3000);
            } else {
                ipList = res;
                if (ipList.length > 0) {
                    console.log('ip count');
                    console.log(ipList.length);

                    setProxy();
                    changeIp();

                    // setInterval(() => {
                    //     changeIp();
                    // }, 300 * 1000);
                    getAlbum();
                } else {
                    console.log('no ip');

                }
            }
        });
        connection1.end();
    }
    getIpList();

    function getAlbum(options) {
        var connection2 = mysql.createConnection(mysqlCloudMusic);
        var query2 = `select * from album where (ISNULL( song_updated )) limit 1 offset ${offset}`;
        console.log(query2);
        console.log();

        connection2.query(query2, function (err, res) {
            if (err) {
                console.log(err);

            } else {
                console.log('get album success');
                console.log(res);
                console.log();

                if (res.length === 0) {
                    console.log('no album');
                    setTimeout(function () {
                        getAlbum();
                    }, 3600 * 1000);
                } else {
                    var album = res[0];

                    fn2(album);
                }
            }
        });
        connection2.end();
    }

    function fn2(album) {
        const albumId = album.id;
        const artistId = album.artist_id;

        var url = `https://music.163.com/album?id=${albumId}`;
        superagent.get(url)
            .timeout(3000)
            // .proxy(proxy)
            .end(function (err2, res2) {
                console.log(url);
                
                if (err2) {
                    console.log('http err');
                    console.log(url);

                    setTimeout(() => {
                        changeIp();
                        // getSongList();
                        fn2(album);
                    }, 3000);
                } else {
                    console.log('http success');
                    var text = res2.text;
                    fs.writeFile('html/song.html', text, function () { });

                    fs.writeFile('html/song.html', text, function () {})

                    if (/你要查找的网页找不到/g.test(text)) {
                        console.log('你要查找的网页找不到');
                        console.log();
                        feedback(album);
                    } else {
                        if ((/专辑 - 网易云音乐/g).test(text)) {

                            var $ = cheerio.load(text);

                            var e1 = $('.n-songtb').eq(0);
                            var e2 = e1.find('.u-title .sub');
                            var text1 = e2.text();
                            if (text1 === '0首歌') {
                                feedback(album);
                            } else {
                                var songListElement = $('#song-list-pre-cache');
                                if (songListElement.length > 0) {
                                    var list2 = songListElement.find('.f-hide>li');

                                    const songList = [];
                                    list2.each((i, element) => {
                                        var item = list2.eq(i);

                                        var href = item.find('a').eq(0).attr().href;
                                        var id = Number(href.replace(/\/song\?id=/g, ''));

                                        var songName = item.text();
                                        var song = [id, songName, artistId, albumId];

                                        songList.push(song);
                                    });

                                    console.log(songList);
                                    if (songList.length > 0) {
                                        const options = {
                                            album: album,
                                            songList: songList
                                        };
                                        upload(options);
                                    } else {
                                        feedback(album);
                                    }

                                } else {
                                    changeIp();
                                    fn2(album);
                                }
                            }
                        } else {
                            changeIp();
                            fn2(album);
                        }

                    }
                    


                }
            });
    }

    function upload(options) {
        console.log(options);
        const album = options.album;
        const songList = options.songList;

        var connection3 = mysql.createConnection(mysqlCloudMusic);
        connection3.connect();
        var query3 = 'insert ignore into song(id,name,artist_id,album_id) values ?';
        connection3.query(query3, [songList], function (err3, res3) {
            console.log('query3 end');
            if (err3) {
                console.log('query3 err');
                console.log(err3);

            } else {
                console.log('query3 success');
                console.log(res3);
                feedback(album);
            }

        });
        connection3.end();
    }


    function feedback(album) {
        const albumId = album.id;

        var connection4 = mysql.createConnection(mysqlCloudMusic);
        var query4 = `update album set song_updated=1 where id=${albumId}`;
        connection4.connect();
        connection4.query(query4, function (err4, res4) {
            console.log('query4 end');
            if (err4) {
                console.log('query4 err');

            } else {
                console.log('query4 success');
                console.log(res4);
                console.log('feedback end');
                setTimeout(() => {
                    getAlbum();
                }, 2000);
            }
        });
        connection4.end();
    }

}
for (let i = 0; i < 1; i++) {
    console.log(i);
    const offset = 10 * i;
    main({
        offset: offset
    });
}